def romanToInt(s):
    table = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    res = 0
    i = 0
    while i < len(s):
        if i + 1 < len(s) and table[s[i]] < table[s[i + 1]]:
            res -= table[s[i]]
        else:
            res += table[s[i]]
        i += 1
    return res


print(romanToInt("III"))  # 3
print(romanToInt("IV"))  # 4
print(romanToInt("IX"))  # 9
print(romanToInt("LVIII"))  # 58
print(romanToInt("MCMXCIV"))  # 1994
